package topofstack.networkserverutils.net;

import java.io.BufferedReader;
import java.io.StringReader;

import topofstack.networkserverutils.bean.TraceRouteInfo;
import topofstack.networkserverutils.util.ShellEmulator;

public class TraceRoute {
	
	public static final int SITE_NAME_INDEX = 2;
	public static final int SITE_IP_INDEX = 4;
	
	public static TraceRouteInfo get(String url) {
		String command = "traceroute " + url;
		String result = ShellEmulator.query(command);

		return parse(result);
	}

	private static TraceRouteInfo parse(String input) {
		if (input == null)
			return null;

		BufferedReader reader = new BufferedReader(new StringReader(input));
		TraceRouteInfo traceRouteInfo = new TraceRouteInfo();

		try {
			String line = reader.readLine();
			while ((line = reader.readLine()) != null) {
				String[] contents = line.trim().split("[ ()]");
				traceRouteInfo.add(contents[SITE_NAME_INDEX], 
						contents[SITE_IP_INDEX]);
			}
		} catch (Exception exception) {
			exception.printStackTrace();
			return null;
		}

		return traceRouteInfo;
	}
}
